<?php
namespace app\modules\web\controllers\common;

use app\common\components\BaseWebController;
use app\common\service\applog\AppLogService;
use app\common\service\UrlService;
use app\models\User;

//web 统一控制器当中 做一些web独有的验证
//1.指定特定的布局文件
//2.进行登录验证
class BaseController extends BaseWebController
{
    protected $page_size = 50;
    public $current_user = null;
    protected $auth_cookie_name = "imooc_book";
    public $layout = 'main';
    public $allowAllAction = [
        'web/user/login'
    ];
    //登录统一验证
    public function beforeAction($action)
    {
        if( in_array( $action->uniqueId,$this->allowAllAction ) ){
            return true;
        }

        $is_login = $this->checkLoginStatus();
        if( !$is_login ){
            if( \Yii::$app->request->isAjax ){
                $this->renderJson([],"未登录，请先登录~~~",-302);
            } else {
                return $this->redirect( UrlService::buildWwwUrl( 'user/login' ) );
            }
            return false;
        }


        //记录所有用户的访问
        AppLogService::addAppAccessLog( $this->current_user['uid'] );

        return true;

        return $this->redirect( UrlService::buildWwwUrl( 'user/login' ) );
        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }

    /**
     * @return bool
     * 验证当前登录是否有效
     */
    public function checkLoginStatus()
    {
        $auth_cookie = $this->getCookie( $this->auth_cookie_name,'' );
        if( !$auth_cookie ){
            return false;
        }

        list( $auth_token,$uid ) = explode('#',$auth_cookie);
        if( !$auth_token || !$uid ){
            return false;
        }

        if( !preg_match('/^\d+$/',$uid) ){
            return false;
        }

        $user_info = User::find()->where(['uid'=>$uid])->one();
        if( !$user_info ){
            return false;
        }

        $auth_token_md5 = md5( $user_info['login_name'].$user_info['login_pwd'].$user_info['login_salt'] );
        if( $auth_token_md5 != $auth_token  ){
            return false;
        }

        $this->current_user = $user_info;

        return true;
    }

    //设置登录态的方法
    public function setLoginStatus( $user_info )
    {
        $auth_token = $this->geneAuthToken( $user_info );
        $this->setCookie( $this->auth_cookie_name,$auth_token.'#'.$user_info['uid'] );
    }

    //删除登录态
    public function removeLoginStatus()
    {
        $this->removeCookie( $this->auth_cookie_name );
    }

    //统一生成加密字串
    public function geneAuthToken( $user_info )
    {
        return md5( $user_info['login_name'].$user_info['login_pwd'].$user_info['login_salt'] );
    }
}